/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
var geocoder;
var resposta;

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}

function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng);
}

function errorFunction() {
    resposta = "Erro API Google";
}

function getLocalidade() {
    geocoder = new google.maps.Geocoder();
    
    return resposta;
}

function codeLatLng(lat, lng) {
    alert(resposta);
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            console.log(results);
            if (results[1]) {
                resposta = results[0].address_components[2].short_name + "," + results[0].address_components[4].short_name;
            } else {
                resposta = "Sem resultados";
            }
        } else {
            resposta = "Geocoder failed due to: " + status;
        }
    });
    alert(resposta);
}

$(document).ready(function(){
   $("#localidade").val(getLocalidade());
});
